package com.tqjc.work;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.tqjc.entity.PublicResult;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Description: 线程池操作,单例模式实现
 * @author: pzy
 * @date: 2023年05月18日 11:09
 */

@Slf4j
public class ThreadPoolOperator {



    //核心线程池数量
    static Integer corePoolSize = 10;

    //最大线程数
    static Integer maximumPoolSize = 12;

    //最大空闲时间
    static Integer keepAliveTime = 1;

    //最大空闲时间单位
    static TimeUnit timeUnit = TimeUnit.MINUTES;

    //阻塞队列
    static BlockingDeque<Runnable> workQue = new LinkedBlockingDeque<>();




    //线程池工厂
//    使用谷歌guava创建线程池
    static ThreadFactory threadFactory = new ThreadFactoryBuilder().build();

    private static volatile ThreadPoolOperator instance;

    private ThreadPoolOperator() {}

    public static ThreadPoolOperator getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolOperator.class) {
                if (instance == null) {
                    instance = new ThreadPoolOperator();
                }
            }
        }
        return instance;
    }


    //创建线程池
    private static ThreadPoolExecutor CORE_POOL = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, workQue, threadFactory);


    /**
     * create by: pzy
     * description: 提交工作步骤
     * create time: 2023/5/22 10:05
     *
     * @return void
     * @param: [craneId]
     */
    public Future submitStep(Callable<PublicResult> callable) {
        try{
            PublicResult publicResult = new PublicResult();
            //使用线程池阻塞
            return CORE_POOL.submit(callable);
        }catch (Exception e){
           return null;
        }
//
    }


    /**
     * create by: pzy
     * description: 提交工作线程
     * create time: 2023/5/22 10:05
     *
     * @return void
     * @param: [craneId]
     */
    public Future submitWorkThread(Runnable runnable) {
        try{
            return CORE_POOL.submit(runnable);
        }catch (Exception e){
            return null;
        }

    }


    //停止工作线程

    public void interruptWorkThread(Runnable runnable) {

        CORE_POOL.remove(runnable);

    }


}
